import cache from './cache'
import config from './config'
import Vue from 'vue'
import store from '@/store/index'
import * as api from '@/api/index'
import thirdApi from '@/api/third'
const tools={
    getToken(){
        return cache.get('token')
    },
    prePage(length=-2,$returnVm=true){
        let pages = getCurrentPages();
        let prePage = pages[pages.length + length];
        // #ifdef H5
        return prePage;
        // #endif
        if(!$returnVm) return prePage
        return prePage.$vm
    },
    prePageRoute(length=-2){
        let pages = getCurrentPages();
        let prePage = pages[pages.length +length];
        return prePage!==undefined ? prePage.route:''
    },
    msg(title, duration=1500, mask=false, icon='none'){

        return new Promise(resolve => {
            if(Boolean(title) === false){
                return;
            }
            uni.showToast({
                title,
                duration,
                mask,
                icon,
                success:()=>{
                    setTimeout(function () {
                        resolve(true)
                    },duration)

                }
            });
        })

    },
    success(title='操作成功', duration=800, mask=false, icon='none'){
        return new Promise(resolve => {
            uni.showToast({
                title,
                duration,
                mask,
                icon,
                success:()=>{
                    setTimeout(function () {
                        resolve(true)
                    },duration)
                }
            });


        })


    },
    delConfirm(content,title=''){
        //统一提示方便全局修改
        if(Boolean(content) === false){
            return;
        }
        return new Promise((resolve)=>{
            uni.showModal({
                title:'提醒',
                content: content,
                confirmText:'删除',
                confirmColor:'#f00',
                success: function (res) {
                    if (res.confirm) {
                        resolve(true)
                    } else if (res.cancel) {
                        resolve(false)
                    }
                }
            });
        })

    },
    /**
     * 将rpx或px转换为px单位
     * @param {String} vaule
     */
    toPx(value) {
        const result = /(\d+\.?\d*)(\w+)/.exec(value);
        if ('rpx' === result[2].trim()) {
            return uni.getSystemInfoSync().screenWidth * Number(result[1]) / 750;
        } else if('px' === result[2].trim()) {
            return Number(result[1]);
        } else {
            throw new TypeError(`${value}单位格式不正确`);
        }

    },
    ////获取字符串的真实长度（字节长度）
    strLeng(str) {
        if(str) {
            let len = str.length, truelen = 0;
            for(let x = 0; x < len; x++) {
                if(str.charCodeAt(x) > 128){
                    truelen += 2;
                }else{
                    truelen += 1;
                }
            }
            return truelen;
        } else {
            return 0;
        }
    },
    ////计算页数
    getPageNum(total,row) {
        let num = Number(total) / Number(row);
        //是否为整数
        if(num%1 !== 0) {
            let b = num.toString();	//转字符串
            let a = parseInt(b.substring(0,b.indexOf('.')));	//取小数点前
            let s = b.replace(/\d+\.(\d*)/, '$1');	//取小数点后
            if(s > 0) {
                num = a + 1;
            }
        }
        return num;
    },
    j(path=''){
        return config.ossUrl+path
    },
    url(path){
        return config.baseURL+path
    },
    /**
     * 对比数组元素是否相同
     * @arr1            {array}     待判断数组 1
     * @arr2            {array}     待判断数组 2
     * */
    checkArrSame (arr1, arr2)  {

        // 数组合并
        const sumArr = [...arr1, ...arr2];
        // 数组去重
        const newArr = [...new Set(sumArr)];
        // 根据数组长度对比返回结果
        return [...new Set(arr1)].length === newArr.length;
    },
    //数组去重
    array_unique(array){
        return [...new Set(array)]
    },
    deepClone(obj) {
        return JSON.parse(JSON.stringify(obj))
    },

    //用户信息
    user(){
          console.log('tools user 获取到用户信息store.getters.user')
          console.log(store.getters.user)
        return store.getters.user
    },
    location(){
        return store.getters.address_info ?  store.getters.address_info : cache.get('location')
    },
    userInfo(){
       return new Promise(resolve => {
           if(!this.user() && this.getToken()){
               store.dispatch('user/getInfo').then(res=>{
                    resolve(res)
               })
           }else if(this.user()){
               resolve(this.user())
           }
       })
    },
    wx_login_info(){
            return new Promise(resolve => {
                if(!tools.isEmpty(store.getters.wx_login_info)){
                    resolve(store.getters.wx_login_info)

                }else{
                    store.dispatch('wxLoginInfo/login').then(res=>{
                        if(res){
                            resolve(res)
                        }
                    })
                }
            })
    },
    redirectLogin(url=false){
        let currentUrl = url ? url : tools.getCurrentPageUrlWithArgs()
        if(currentUrl && currentUrl!=='/pages/public/login')  cache.put('loginReturnUrl',currentUrl)
        this.goTo('/pages/public/login')
    },
    //获取当前页完整URL路径包括参数
     getCurrentPageUrlWithArgs() {
        const pages = getCurrentPages()
        const currentPage = pages[pages.length - 1]
        const url = currentPage.route
        const options = currentPage.options
        let urlWithArgs = `/${url}?`
        for (let key in options) {
            const value = options[key]
            urlWithArgs += `${key}=${value}&`
        }
        urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
        return urlWithArgs
    },
    //处理
    exceptionResponse(res){
        console.log('exceptionResponse')
        console.log(res.status)
        switch (res.status) {
            //登录处理
            case 1001:
                console.log('跳登录')
                this.msg('请登录^_^')
                break;
            default:
                console.log('res.message')
                console.log(res)
               // this.msg(res.msg)
                uni.showModal({title:'错误-'+res.status,content:res.msg})
                break;
        }
    },
    conifg(name){
        return config.name!=undefined ? config.name:'';
    },

    loginSuccess(){
        let returnUrl = cache.get('loginReturnUrl')
        let defaultUrl = '/pages/index/index?page=user'
        cache.remove('loginReturnUrl')
        uni.reLaunch({url:(returnUrl ? returnUrl:defaultUrl)})
    },
    thumb(imgurl, w, h) {
        if(imgurl && !imgurl.includes(config.ossDomain)) return imgurl
        if(imgurl!==undefined && imgurl){
            var suffix = [];
            if (w && parseInt(w)) {
                suffix.unshift('w_' + w);
            }
            if (h && parseInt(h)) {
                suffix.unshift('h_' + h);
            }
            if (suffix.length > 0) {
                suffix.unshift('limit_0');
                suffix.unshift('Q_100');
                suffix.unshift('m_fill');
                suffix.unshift('x-oss-process=image/resize');
            }
            return imgurl + '?' + suffix.join(',');
        }
    },
    goTo(url,params,replace=false){
        let sourceUrl  = url
        let pos        = url.indexOf('?',url)
        let clean_url  = pos===-1 ? url :  url.substring(0,url.indexOf('?',pos))
        let routeArr   = Vue.prototype.$routeConf
        let index      = routeArr.findIndex(v=>v.page===clean_url)
        if(params){
            let temp=[]
            for(let i in params){
                temp.push(`${i}=${params[i]}`)
            }
            sourceUrl=sourceUrl+'?'+temp.join('&')

            console.log('带参数的跳转链接是'+sourceUrl)
        }

        if(index!==-1 && routeArr[index].requireAuth && !this.user()){
            this.redirectLogin(sourceUrl)
        }else{
            if(clean_url==='/pages/index/index') replace = true
            if(replace===true){
                console.log('replace跳')
                uni.redirectTo({url:sourceUrl, success:res=>{}, fail:err=>{
                    console.log(err)
                   // uni.reLaunch({url:'/pages/index/index'})
                }})
            }else{
                console.log('navigate跳')
                uni.navigateTo({url:sourceUrl, success:res=>{}, fail:err=>{
                    console.log(err)
                    uni.reLaunch({url:'/pages/card/home/home'})
                }})
            }
        }

    },
    pageTitle(name){
        let routeArr = Vue.prototype.$routeConf
        let index    = routeArr.findIndex(v=>v.name===name)
        return index!==-1 ? routeArr[index].title :this.conifg('appName');
    },
    dev(){
        return this.msg('正在紧急开发中...')
    },
    isEmpty(obj){
        if (obj == null) return true
        if (obj.length > 0) return false
        if (obj.length === 0) return true
        if (typeof obj !== 'object') return true
        for (var key in obj) {
            if (hasOwnProperty.call(obj, key)) return false
        }
        return true

    },
    rmOssUrl(url){
        return url.substring(url.lastIndexOf('.com/')+5,url.length)
    },
    /**
     * 质量压缩
     */
    getCanvasImg(obj,ctx,pathSize, canvasWidth, canvasHeight, quality) {
        return new Promise(resolve => {

            let {path,size} = pathSize
                ctx.clearRect(0, 0, canvasWidth, canvasHeight);
                ctx.drawImage(path, 0, 0, canvasWidth, canvasHeight);
                setTimeout(function() {
                    ctx.draw(false, e => {
                        uni.canvasToTempFilePath({
                            canvasId: 'attendCanvasId',
                            destWidth: canvasWidth,
                            destHeight: canvasHeight,
                            fileType: 'jpg',
                            quality: quality,
                            success: res => {
                                uni.getFileInfo({
                                    filePath:res.tempFilePath,
                                    success (res1) {
                                    }
                                })
                                resolve(res.tempFilePath)
                            },
                            fail:err=>{
                                console.log(err)
                            }
                        }, obj)
                    })
                },1000)
            })
    },


    /**
     *   //压缩比例
     * @param imageSize
     * @param maxWidth 最大尺寸限制// 最大尺寸限制
     * @param maxHeight
     */
    imageReSize: function (imageSize, maxWidth, maxHeight) {
        let originWidth   = imageSize.width
        let originHeight  = imageSize.height
        // 目标尺寸
        var targetWidth  = originWidth,
            targetHeight = originHeight;
        //等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
        if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
                // 要求宽度*(原生图片比例)=新图片尺寸
                targetWidth = maxWidth;
                targetHeight = Math.round(maxWidth * (originHeight / originWidth));
            } else {
                targetHeight = maxHeight;
                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
            }

        }
        return {width:targetWidth,height:targetHeight}
    },
    getCurrTime(){

        let date = (new Date()).toLocaleDateString()//获取当前日期
        let time = (new Date()).toLocaleTimeString()//获取当前日期

            date =date.replace(/\//g,'-');//替换2017/05/03 为    2017-05-03


        return    `${date} ${time}`;
    },
    tapRoot(){
        this.$store.dispatch('dropMenu/showHide',false)
    },
    upload(file){
        let _this = this
        return new Promise(resolve => {
            if(file.includes('//tmp')){
                console.log('上传')
                thirdApi.uploadFile(file).then(res=>{
                    if(res){
                        console.log('上传结果')
                        console.log(res)
                       /// resolve(_this.rmOssUrl(res))
                        resolve(res)
                    }
                })
            }else{
                console.log('不上传')
                console.log(file)
                resolve(file)
            }
        })

    },
    async sleep(secend){
        await new Promise(resolve => {
            setTimeout(resolve,secend)
        })
    },
    dialogLogin(url,obj){
        if(!tools.user()){
            obj.$refs['loginRef'].setRedirectUrl(url).show();
        }else{
            tools.goTo(url)
        }
    },
    formatMachineInfo(res){
        //品牌  型号 微信版本号  操作系统及版本
        let key=['model','platform','system','brand','version',];
        let machinInfo = key.map((item,index,array)=>{
            let keys =Object.keys(res)
            if(keys.includes(item)){
                return array[item] = res[item];
            }
        })
        return machinInfo.join(' | ');
    },
    //机器
    async machineInfo(systemInfo,userInfo){
        console.log('machineInfo')
        console.log(userInfo)
        let machine_info = this.formatMachineInfo(systemInfo);
        let {openid}     = userInfo
        let res = await api.machine({machine_info,openid})
        if(res) console.log('machine ok')
    },
    getCurrentPageUrl(){
        let pages = getCurrentPages();
        let prePage = pages[pages.length - 1];
        return prePage!==undefined ? prePage.route:''
    },
    sceneParam(options){
        //扫描小程序码进入 -- 解析携带参数
        if(!options.scene) return options
        let param = decodeURIComponent(options.scene);
        let info = param.split('&');
        let res ={};
        for(let i in info){
            let temp = info[i].split('=');
            res[temp[0]] = temp[1];
        }
        return {...options,...res};
    },
    in_array(search,array){
        if(array){
            for(var i in array){
                if(array[i]==search){
                    return true;
                }
            }
        }
        return false;
    },
    editBaseInfo(){
        console.log('清空缓存再跳')
        store.dispatch('address/set')
        this.goTo('profile')
    },
    previewImage(url,force=false){
        //console.log(this.url+'?rand='+Math.random());
        uni.previewImage({current:url, urls:[url+(force ? '?rand='+Math.random():'')]})
    },
    mThumb(url,w){
        return `${url}_${w}x${w}.jpg`;
    }

}
Vue.prototype.$cache = cache
Vue.prototype.$tools = tools
export default tools
